#include "CDatabaseManager.h"
#include <QFile>
#include <QDebug>
#include <QThread>

CDatabaseManager::CDatabaseManager(QObject *parent) : QObject(parent)
{

}

CDatabaseManager::~CDatabaseManager()
{
    foreach(QString strKey,m_mapDataBase.keys()){
        QSqlDatabase *pDatabase = m_mapDataBase[strKey];
        if(pDatabase){
            pDatabase->close();
            delete pDatabase;
            pDatabase = nullptr;
        }
        QSqlDatabase::removeDatabase(strKey);
    }
}

CDatabaseManager *CDatabaseManager::instance()
{
    static CDatabaseManager* m_pInstance = nullptr;
    if(m_pInstance == nullptr){
        if(m_pInstance == nullptr){
            m_pInstance = new CDatabaseManager();
        }
    }
    return m_pInstance;
}

bool CDatabaseManager::init(QString strDbFilename)
{
    m_strDbFilename = strDbFilename;

    if(!QFile::exists(strDbFilename)){
        qWarning("数据库文件不存在:%s 创建数据库文件...",strDbFilename.toUtf8().data());
        getDbConnection();
    }

    return true;
}

bool CDatabaseManager::setSynMode(SynMode mode)
{
    //@TODO 测试未发现明显变化
    QString strSql;
    switch (mode) {
    case SynMode::Full:
        strSql = "PRAGMA synchronous = FULL;";
        break;
    case SynMode::Normal:
        strSql = "PRAGMA synchronous = NORMAL;";
        break;
    case SynMode::Off:
        strSql = "PRAGMA synchronous = OFF;";
        break;
    default:
        strSql = "PRAGMA synchronous = FULL;";
        break;
    }
    QSqlQuery query(*getDbConnection());
    bool bOk = query.exec(strSql);
    qDebug()<<"同步："<<bOk<<strSql;
    return bOk;
}

QSqlDatabase *CDatabaseManager::getDbConnection()
{
    QString strDbConnectName = QString::number((quintptr)QThread::currentThread());

    if(!m_mapDataBase.contains(strDbConnectName)){
        QSqlDatabase *pDatabase = new QSqlDatabase();
        *pDatabase = QSqlDatabase::addDatabase("QSQLITE",strDbConnectName);
        pDatabase->setDatabaseName(m_strDbFilename);
        if(!pDatabase->isOpen()){
            if(pDatabase->open()){
                qInfo()<<"数据库连接打开成功! 连接名:"<<strDbConnectName<<pDatabase->databaseName();
            }else{
                qWarning()<<"数据库连接打开失败! 连接名:"<<strDbConnectName<<"当前所有连接："<<m_mapDataBase;
            }
        }
        m_mapDataBase.insert(strDbConnectName,pDatabase); //@TODO 线程销毁的时候，移除连接，避免持续增多
        qInfo()<<"DataBase connect count:"<<m_mapDataBase.count();
        return pDatabase;
    }

    return m_mapDataBase.value(strDbConnectName);
}

